package leetcode;

/**
 * @author niann
 * @description 旋转链表
 * //TODO https://leetcode.cn/problems/rotate-list/description/
 * @since 2023/12/28 下午7:49
 **/
public class LeetCode61 {
//    Tips:   比如k=2 最右边的节点移动二次就好
//    source: 1,2,3,4,5
//    第一次： 5，1，2，3，4
//    第二次： 4，5，1，2，3

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode rotateRight(ListNode head, int k) {

        if (k == 0 || head == null || head.next == null) {
            return head;
        }
        //获取链表长度
        int len = getLen(head);
        k = k % len;
        if (k == len) {
            return head;
        }
        for (int i = 0; i < k; i++) {
            var cur = head;
            var next = cur.next;
            ListNode prev = null;
            while (next != null) {
                prev = cur;
                cur = next;
                next = cur.next;
            }
            prev.next = null;
            cur.next = head;
            head = cur;
        }
        return head;
    }

    private int getLen(ListNode head) {
        int len = 0;
        while (head != null) {
            len++;
            head = head.next;
        }
        return len;
    }
}
